package com.talent.jiwen.base;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.afollestad.materialdialogs.MaterialDialog;
import com.jaeger.library.StatusBarUtil;
import com.talent.jiwen.ActivityManager;
import com.talent.jiwen.R;
import com.talent.jiwen.http.common.ActivityLifeCycleEvent;
import com.talent.jiwen.util.MaterialDialogUtil;
import com.talent.jiwen.util.ReflectionUtil;

import org.greenrobot.eventbus.EventBus;

import butterknife.ButterKnife;
import rx.subjects.PublishSubject;


public abstract class BaseActivity extends AppCompatActivity {

    private ViewFlipper mContentView;
    protected RelativeLayout mHeadLayout;
    protected ImageView mBtnLeft;
    protected Button mBtnRight;
    protected TextView mTitle;
    protected TextView mHeadRightText;
    private Drawable mBtnBackDrawable;
    protected View view_sp;

    protected Context mContext;
    public final PublishSubject<ActivityLifeCycleEvent> lifecycleSubject = PublishSubject.create();

    protected abstract int provideContentViewId();//用于引入布局文件

    public abstract String titleName();

    protected abstract void initData();//处理布局和布局一些数据

    protected int firstPage = 1;

    protected int pageNo = 1; //当前页数
    protected int pageNoMax;  //最大页数
    protected boolean isCheck = true;//刷新还是加载
    protected static final String pageSize = "20";//每次加载页数

    private boolean destroyed = false;
    private static Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.activity_base);
        StatusBarUtil.setColor(this, getResources().getColor(R.color.white),100);
        mContext = this;
        initView();
        ButterKnife.bind(this);
//        App.addActivity(this);
        ActivityManager.getAppManager().addActivity(this);
//        registEventBus();
        initData();
    }


    private void initView(){

        mContentView = (ViewFlipper) super.findViewById(R.id.layout_container);
        mHeadLayout = (RelativeLayout) super.findViewById(R.id.layout_head);
        mHeadRightText = (TextView) findViewById(R.id.text_right);
        mBtnLeft = (ImageView) super.findViewById(R.id.btn_left);
        mBtnRight = (Button) super.findViewById(R.id.btn_right);
        mTitle = (TextView) super.findViewById(R.id.tv_title);
        view_sp=super.findViewById(R.id.view_sp);
        mBtnBackDrawable = getResources().getDrawable(R.drawable.ac_back_icon);
        mBtnBackDrawable.setBounds(0, 0, mBtnBackDrawable.getMinimumWidth(),
                mBtnBackDrawable.getMinimumHeight());
        setContentView(provideContentViewId());
        setTitle(titleName());

    }



    @Override
    public void setContentView(View view) {
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, 1);
        mContentView.addView(view, lp);
    }

    @Override
    public void setContentView(int layoutResID) {
        View view = LayoutInflater.from(this).inflate(layoutResID, null);
        setContentView(view);
    }



    /**
     * 设置头部是否可见
     *
     * @param visibility
     */
    public void setHeadVisibility(int visibility) {
        mHeadLayout.setVisibility(visibility);
    }

    /**
     * 设置左边是否可见
     *
     * @param visibility
     */
    public void setHeadLeftButtonVisibility(int visibility) {
        mBtnLeft.setVisibility(visibility);
    }

    /**
     * 设置右边是否可见
     *
     * @param visibility
     */
    public void setHeadRightButtonVisibility(int visibility) {
        mBtnRight.setVisibility(visibility);
    }

    /**
     * 设置标题
     */
    public void setTitle(int titleId) {
        setTitle(getString(titleId), false);
    }

    /**
     * 设置标题
     */
    public void setTitle(int titleId, boolean flag) {
        setTitle(getString(titleId), flag);
    }

    /**
     * 设置标题
     */
    public void setTitle(String title) {
        setTitle(title, false);
    }


    /**
     * 设置标题
     *
     * @param title
     */
    public void setTitle(String title, boolean flag) {
        mTitle.setText(title);
//        if (flag) {
//            mBtnLeft.setCompoundDrawables(null, null, null, null);
//        } else {
//            mBtnLeft.setCompoundDrawables(mBtnBackDrawable, null, null, null);
//        }
    }


    /**
     * 点击左按钮
     */
    public void onHeadLeftButtonClick(View v) {
        finish();
    }

    /**
     * 点击右按钮
     */
    public void onHeadRightButtonClick(View v) {

    }

//    public Button getHeadLeftButton() {
//        return mBtnLeft;
//    }
//
//    public void setHeadLeftButton(Button leftButton) {
//        this.mBtnLeft = leftButton;
//    }
    public ImageView getHeadLeftButton() {
        return mBtnLeft;
    }

    public void setHeadLeftButton(ImageView leftButton) {
        this.mBtnLeft = leftButton;
    }

    public Button getHeadRightButton() {
        return mBtnRight;
    }

    public void setHeadRightButton(Button rightButton) {
        this.mBtnRight = rightButton;
    }

    public Drawable getHeadBackButtonDrawable() {
        return mBtnBackDrawable;
    }

    public void setBackButtonDrawable(Drawable backButtonDrawable) {
        this.mBtnBackDrawable = backButtonDrawable;
    }



    //    跳转
    protected void intentActivity(Class<? extends Activity> intentActivity) {
        Intent intent = new Intent(mContext, intentActivity);
        startActivity(intent);
    }


    //    传递带参数
    protected void intentBundleActivity(Class<? extends Activity> intentActivity, Bundle bundle) {
        Intent intent = new Intent(mContext, intentActivity);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    //   吐司
    protected void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }



    /**
     * @description 注册eventbus
     */
    protected void registEventBus() {
        EventBus.getDefault().register(this);
    }

    /**
     * @description 注销eventbus
     */
    protected void unRegistEventBus() {
        EventBus.getDefault().unregister(this);
    }



    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (null != this.getCurrentFocus() && event.getAction() == MotionEvent.ACTION_UP) {
            InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            return mInputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        }
        return super.onTouchEvent(event);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
//        unRegistEventBus();
        ActivityManager.getAppManager().finishActivity(this);
        lifecycleSubject.onNext(ActivityLifeCycleEvent.DESTROY);
        destroyed = true;
    }


    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }

    protected void showKeyboard(boolean isShow) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

        if (isShow) {
            if (getCurrentFocus() == null) {
                imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
            } else {
                imm.showSoftInput(getCurrentFocus(), 0);
            }
        } else {
            if (getCurrentFocus() != null) {
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }

        }
    }

    /**
     * 延时弹出键盘
     *
     * @param focus ：键盘的焦点项
     */
    protected void showKeyboardDelayed(View focus) {
        final View viewToFocus = focus;
        if (focus != null) {
            focus.requestFocus();
        }
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                if (viewToFocus == null || viewToFocus.isFocused()) {
                    showKeyboard(true);
                }
            }
        }, 200);
    }



    protected final Handler getHandler() {
        if (handler == null) {
            handler = new Handler(getMainLooper());
        }
        return handler;
    }

    @Override
    public void onBackPressed() {
        invokeFragmentManagerNoteStateNotSaved();
        super.onBackPressed();
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void invokeFragmentManagerNoteStateNotSaved() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            ReflectionUtil.invokeMethod(getFragmentManager(), "noteStateNotSaved", null);
        }
    }

    /**
     * 判断页面是否已经被销毁（异步回调时使用）
     */
    protected boolean isDestroyedCompatible() {
        if (Build.VERSION.SDK_INT >= 17) {
            return isDestroyedCompatible17();
        } else {
            return destroyed || super.isFinishing();
        }
    }


    @TargetApi(17)
    private boolean isDestroyedCompatible17() {
        return super.isDestroyed();
    }


    public void showClassDialog(){

        MaterialDialog.Builder dialog= MaterialDialogUtil.getCommonDialog(mContext, "上课啦", "你预约的课程已经开始啦!", "立即进入", "取消", new MaterialDialogUtil.OnDialogPoNeClickListener() {
            @Override
            public void onPositive() {


            }

            @Override
            public void onNegative() {

            }
        });

        dialog.show();
    }




}
